package com.kanshu.ksgb.fastread.doudou.module.book.presenter;

import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.BaseMvpPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.DiskLruCacheUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.RecentBookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfGoodBook;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfTopData;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.WrapBookInfos;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.ShelfRequestParams;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.subjects.Subject;


/**
 * Created by wcy on 2017\6\19 0019.
 */

public class ShelfPresenter extends BaseMvpPresenter<ShelfView> {
    ShelfModel mShelfModel = new ShelfModel();
    ShelfTopData mShelfTopInfo;
    List<BookInfo> mBookInfos;

    public ShelfPresenter(Subject<Integer> lifeCyclerSubject) {
        super(lifeCyclerSubject);
    }

    public void getContentInfo(boolean load) {
        if (load) {
            mMvpView.showLoading(null);
        }
        getShelfTopInfo();
        getShelfBooks();
    }

    public void getShelfBooks() {
        final String key;
        key = SettingManager.getShelfBookKey();
        mShelfModel.getShelfBookList(key, new INetCommCallback<WrapBookInfos>() {
            @Override
            public void onResponse(WrapBookInfos bookInfos) {
                if (!isViewAttached()) {
                    return;
                }
                mBookInfos = bookInfos.bookInfos;
                mMvpView.dismissLoading();
                if (!bookInfos.isFromNet) {
                    mMvpView.showShelfBookInfos(bookInfos.bookInfos, false);
                    return;
                }
                Type type = new TypeToken<ArrayList<BookInfo>>() {
                }.getType();
                // 本地缓存的信息
                List<BookInfo> localList = DiskLruCacheUtils.get(SettingManager.getShelfBookKey(), type);
                // 网络数据
                List<BookInfo> bookInfos1 = bookInfos.bookInfos;
                // 网络数据和本地缓存比较
                if (!Utils.isEmptyList(bookInfos1) && !Utils.isEmptyList(localList)) {
                    for (int i = 0; i < localList.size(); i++) {
                        String book_id = localList.get(i).book_id;
                        String update_time = localList.get(i).last_chapter_time;
                        boolean is_update = localList.get(i).is_updated;
                        for (int i1 = 0; i1 < bookInfos1.size(); i1++) {
                            if (bookInfos1.get(i1).book_id.equals(book_id)) {
                                if (!TextUtils.equals(bookInfos1.get(i1).last_chapter_time, update_time)) {
                                    bookInfos1.get(i1).is_updated = true;
                                } else {
                                    bookInfos1.get(i1).is_updated = is_update;
                                }
                            }
                        }
                    }
                }
                // 返回网络数据
                mMvpView.showShelfBookInfos(bookInfos1, true);
                for (BookInfo book : bookInfos1) {
                    SettingManager.getInstance().saveBookChapterCount(book.book_id, Integer.parseInt(book.chapter_count));
                }
                // 缓存最新数据
                DiskLruCacheUtils.put(key, bookInfos1);
            }

            @Override
            public void onError(int code, String errDesc) {
                if (!isViewAttached()) {
                    return;
                }
                mMvpView.dismissLoading();
                showErr();
            }
        });
    }

    /**
     * 保存最新的书架信息
     *
     * @param bookInfos
     */
    public void saveNewShelfBooks(List<BookInfo> bookInfos) {
        DiskLruCacheUtils.put(SettingManager.getShelfBookKey(), bookInfos);
    }

    /**
     * 获取书架上方数据
     */
    public void getShelfTopInfo() {
        ShelfRequestParams params = new ShelfRequestParams();
        params.get_intro_info = "1";
        // 加载网络数据
        mShelfModel.getRecentTopInfos(params, new INetCommCallback<BaseResult<ShelfTopData>>() {
            @Override
            public void onResponse(BaseResult<ShelfTopData> info) {
                if (!isViewAttached()) {
                    return;
                }
                if (info.result.data != null) {
                    if (info.result.data.bianji_haoshu != null) {
                        for (ShelfGoodBook book : info.result.data.bianji_haoshu) {
                            SettingManager.getInstance().saveBookChapterCount(book.book_id, Integer.parseInt(book.chapter_count));
                        }
                    }
                    if (info.result.data.zuijin_yuedu != null) {
                        for (RecentBookInfo book : info.result.data.zuijin_yuedu) {
                            SettingManager.getInstance().saveBookChapterCount(book.book_id, Integer.parseInt(book.chapter_count));
                        }
                    }
                }
                mMvpView.dismissLoading();
                mMvpView.showContent(info.result.data);
            }

            @Override
            public void onError(int code, String errDesc) {
                if (!isViewAttached()) {
                    return;
                }
                mMvpView.dismissLoading();
                showErr();
            }
        });

    }

    private void showErr() {
        if (mShelfTopInfo == null && Utils.isEmptyList(mBookInfos)) {
            mMvpView.showError(Constants.ErrCode.NetErr, "no net");
        }
    }

    /**
     * 最近阅读列表
     *
     * @param params
     */
    public void getRecentInfos(ShelfRequestParams params) {
        params.get_intro_info = "1";
      mShelfModel.getRecentInfos(params, new INetCommCallback<BaseResult<List<RecentBookInfo>>>() {
            @Override
            public void onResponse(BaseResult<List<RecentBookInfo>> info) {
                if (!isViewAttached()) {
                    return;
                }
                mMvpView.dismissLoading();
                mMvpView.showNewRecentBookInfos(info);
            }

            @Override
            public void onError(int code, String errDesc) {
                if (!isViewAttached()) {
                    return;
                }
                mMvpView.dismissLoading();
                mMvpView.showError(code, errDesc);
            }
        });
    }



    /**
     * 删除书籍
     *
     * @param book_ids
     */
    public void deleteRecentBook(final String book_ids) {
        mShelfModel.deleteRecentBook(book_ids, new INetCommCallback<List<String>>() {
            @Override
            public void onResponse(List<String> s) {
                ToastUtil.showMessage(Xutils.getContext(), "删除成功");
                ShelfEvent event = new ShelfEvent(ShelfEvent.DELETE_RECENT_BOOK);
                event.obj = s;
                EventBus.getDefault().post(event);
            }

            @Override
            public void onError(int code, String errDesc) {
                ToastUtil.showMessage(Xutils.getContext(), "删除失败");
            }
        });
    }



    @Override
    public void detachView() {
        mShelfModel.cancel();
        super.detachView();
    }
}
